package com.aimashi.aimashibackendjudgeservice.judge;

import cn.hutool.json.JSONUtil;
import com.aimashi.aimashibackcommon.common.ErrorCode;
import com.aimashi.aimashibackcommon.exception.BusinessException;
import com.aimashi.aimashibackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.aimashi.aimashibackendjudgeservice.judge.codesandbox.CodeSandboxFactory;
import com.aimashi.aimashibackendjudgeservice.judge.codesandbox.CodeSandboxProxy;
import com.aimashi.aimashibackendjudgeservice.judge.strategy.JudgeContext;
import com.aimashi.aimashibackendserviceclient.service.QuestionFeignClient;
import com.aimashi.aimashibackmodel.model.codesandbox.ExecuteCodeRequest;
import com.aimashi.aimashibackmodel.model.codesandbox.ExecuteCodeResponse;
import com.aimashi.aimashibackmodel.model.codesandbox.JudgeInfo;
import com.aimashi.aimashibackmodel.model.dto.question.JudgeCase;
import com.aimashi.aimashibackmodel.model.entity.Question;
import com.aimashi.aimashibackmodel.model.entity.QuestionSubmit;
import com.aimashi.aimashibackmodel.model.enums.QuestionSubmitStatusEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService{
    // 问题服务，用于获取问题信息
    @Resource
    private QuestionFeignClient questionFeignClient;

//    // 问题提交服务，用于获取和更新问题提交信息
//    @Resource
//    private QuestionSubmitService questionSubmitService;

    // 判定管理器，用于执行判定逻辑
    @Resource
    private JudgeManager judgeManager;

    // 代码沙箱类型，从配置文件中获取
    @Value("${codesandbox.type:example}")
    private String type;

    /**
     * 执行判定的方法
     *
     * @param questionSubmitId 问题提交的ID
     * @return 判定完成的问题提交对象
     * @throws BusinessException 如果提交的信息不存在，或者题目不存在，或者题目状态更新错误，抛出此异常
     */
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 获取提交的问题
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        // 如果提交的问题不存在，抛出异常
        if (questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交的信息不存在");
        }

        // 获取问题ID并根据ID获取问题
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.getQuestionById(questionId);
        // 如果问题不存在，抛出异常
        if (question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }

        // 检查提交的状态，如果不在等待状态，抛出异常
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
        }

        // 更新提交问题的状态为运行中
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());;
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        // 如果状态更新失败，抛出异常
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }

        // 创建代码沙箱实例
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        // 使用代理模式包装代码沙箱
        codeSandbox = new CodeSandboxProxy(codeSandbox);

        // 获取提交的代码语言和代码
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        // 获取问题的测试用例
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        // 构建执行代码的请求
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();

        // 执行代码并获取执行结果
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        List<String> ouputList = executeCodeResponse.getOutputList();

        // 构建判定上下文
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(ouputList);
        judgeContext.setJudgeCasesList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);

        // 执行判定逻辑
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);

        // 更新提交问题的状态为成功并保存判定信息
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        System.out.println("questionSubmitUpdate:" + questionSubmitUpdate);
        update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);

        // 如果状态更新失败，抛出异常
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新错误");
        }


        //更新题目通过数到题目表
        Question questionUpdate = new Question();
        if ("Accepted".equals(judgeInfo.getMessage())){
            questionUpdate.setId(questionId);
            questionUpdate.setAcceptedNum(question.getAcceptedNum() + 1);
        }
        System.out.println(judgeInfo.getMessage());
        System.out.println("questionUpdate:" + questionUpdate);
        boolean update1 = questionFeignClient.updateQuestionById(questionUpdate);
        // 如果状态更新失败，抛出异常
        if (!update1){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目表通过数状态更新错误");
        }
        // 获取并返回判定结果
        QuestionSubmit questionSubmitResult = questionFeignClient.getQuestionSubmitById(questionId);
        return questionSubmitResult;
    }
}

//public class JudgeServiceImpl implements JudgeService{
//    @Resource
//    private QuestionService questionService;
//
//    @Resource
//    private QuestionSubmitService questionSubmitService;
//
//    @Resource
//    private JudgeManager judgeManager;
//
//    @Value("${codesandbox.type:example}")
//    private String type;
//
//    @Override
//    public QuestionSubmit doJudge(long questionSubmitId) {
//        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
//        if (questionSubmit == null){
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交的信息不存在");
//        }
//        Long questionId = questionSubmit.getQuestionId();
//        Question question = questionService.getById(questionId);
//        if (question == null){
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
//        }
//        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
//            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
//        }
//        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
//        questionSubmitUpdate.setId(questionSubmitId);
//        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());;
//        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
//        if (!update){
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
//        }
//        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
//        codeSandbox = new CodeSandboxProxy(codeSandbox);
//        String language = questionSubmit.getLanguage();
//        String code = questionSubmit.getCode();
//        String judgeCaseStr = question.getJudgeCase();
//        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
//        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
//        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
//                .code(code)
//                .language(language)
//                .inputList(inputList)
//                .build();
//        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
//        List<String> ouputList = executeCodeResponse.getOutputList();
//        JudgeContext judgeContext = new JudgeContext();
//        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
//        judgeContext.setInputList(inputList);
//        judgeContext.setOutputList(ouputList);
//        judgeContext.setJudgeCasesList(judgeCaseList);
//        judgeContext.setQuestion(question);
//        judgeContext.setQuestionSubmit(questionSubmit);
//        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
//        questionSubmitUpdate = new QuestionSubmit();
//        questionSubmitUpdate.setId(questionSubmitId);
//        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
//        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
//        update = questionSubmitService.updateById(questionSubmitUpdate);
//        if (!update){
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新错误");
//        }
//        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);
//        return questionSubmitResult;
//    }
//}